package com.hzsai.mininote.service.Impl;

import com.hzsai.mininote.common.I18nPool;
import com.hzsai.mininote.common.ResponseRe;
import com.hzsai.mininote.entity.User;
import com.hzsai.mininote.entity.UserVO;
import com.hzsai.mininote.repository.JpaUserRepository;
import com.hzsai.mininote.service.UserService;
import com.hzsai.mininote.util.EncryptUtil;
import lombok.NonNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * @author hzsai
 * @date 2020/1/9 0:06
 * @usage:
 */
@Service
public class UserServiceImpl implements UserService {

    private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    @NonNull
    JpaUserRepository userRepository;

    /**
     * 设置事务
     * 其中的类方法必须是public的，否则事务不生效
     * 注意：rollbackFor设置需要注意：lzc遇到过这样的数据回滚问题！！！
     * 在需要回滚的方法里面务必要抛RuntimeException
     * 使用Spring事务管理器的时候，由Spring来打开、提交、回滚默认是遇到运行时异常才回滚（RuntimeException）
     * @param userVO
     * @return
     */
    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public ResponseRe add(UserVO userVO) {

        User user = new User();
        user.setName(userVO.getName());
        user.setPassword(EncryptUtil.getInstance().SHA1(userVO.getPassword()));
        user.setRegisterTime(LocalDateTime.now());

        boolean existed = userRepository.existsByName(user.getName());

        if (existed) {
            return ResponseRe.fail(400, I18nPool.getWord("user_already_exist"), null);
        }

        // 返回保存的Entity，里面有自动配置好的id
        User t_s = userRepository.save(user);

        logger.debug("数据入库：{}", t_s.toString());

        return ResponseRe.success(200, I18nPool.getWord("success"), null);
    }

    /**
     * 永远不要相信用户的数据
     * 需要自己过滤过而不是直接进行保存
     * @param user
     * @return
     */
    @Override
    public ResponseRe update(User user) {

        User _user = new User();

        userRepository.save(user);

        return ResponseRe.success(200, I18nPool.getWord("success"), null);
    }

    @Override
    public ResponseRe markAsDeleted(User user) {

        boolean deleted = userRepository.markAsDeleteById(user.getId());
        if (deleted) {
            return ResponseRe.success(200, I18nPool.getWord("success"), null);
        }

        return ResponseRe.fail(400, I18nPool.getWord("failed"), null);
    }
}
